package com.multicampus.simplewiki.parser.replacer;

import org.apache.oro.text.regex.MalformedPatternException;
import org.apache.oro.text.regex.MatchResult;
import org.apache.oro.text.regex.Pattern;
import org.apache.oro.text.regex.PatternCompiler;
import org.apache.oro.text.regex.PatternMatcher;
import org.apache.oro.text.regex.Perl5Compiler;
import org.apache.oro.text.regex.Perl5Matcher;

import com.multicampus.simplewiki.ctrl.DocumentManager;
import com.multicampus.simplewiki.model.Document;

public class LinkToHtmlReplacer implements Replacer {
	private DocumentManager documentManager;
	
	private static Pattern internalPattern1 = null;
	private static Pattern externalPattern1 = null;
	private static Pattern externalPattern2 = null;
	
	public void setDocumentManager(DocumentManager documentManager) {
		this.documentManager = documentManager;
	}

	public LinkToHtmlReplacer() {
		PatternCompiler compiler = new Perl5Compiler();
		try {
			if (internalPattern1 == null)
				internalPattern1 = compiler.compile("(\\[)([^\\[\\|\\]]*)(\\])");

			if (externalPattern1 == null)
				externalPattern1 = compiler.compile("(\\[)(http://.+)(\\])");

			if (externalPattern2 == null)
				externalPattern2 = compiler.compile("(\\[)([^\\[\\|\\]]*)\\|(http://[a-z|A-Z|\\.]+)(\\])");
		} catch (MalformedPatternException e) {

		}
	}

	public String replace(String contents) {
		String htmlString = null;
		PatternMatcher matcher = new Perl5Matcher();

		if (matcher.contains(contents, externalPattern1)) {
			MatchResult result = matcher.getMatch();
			htmlString = "<a href=\"" + result.group(2) + "\">" + result.group(2) + "</a>";
		}
		else if (matcher.contains(contents, externalPattern2)) {
			MatchResult result = matcher.getMatch();
			htmlString = "<a href=\"" + result.group(3) + "\">" + result.group(2) + "</a>";
		}
		else if (matcher.contains(contents, internalPattern1)) {
			MatchResult result = matcher.getMatch();
			String pageName = result.group(2);
			
			Document existingDoc = documentManager.findByTitle(pageName);
			
			if(existingDoc != null)
				htmlString = "<a href=\"/simplewiki/view_page.do?id=" + existingDoc.getId() + "\">" + pageName + "</a>";
			else
				htmlString = "<a href=\"/simplewiki/newView_page.do?parentId=${parentId}&title=" + pageName + "\">" + pageName + "</a>";
		}
		
		return htmlString;
	}

}
